package org.example.myleet.learn.bounce;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

public class BounceFrame extends JFrame {

    private BallComponent ballComponent;
    private static final int STEPS = 1000;
    private static final long DELAY = 3L;

    public BounceFrame() throws HeadlessException {
        setTitle("Bounce");
        ballComponent = new BallComponent();
        add(ballComponent, BorderLayout.CENTER);
        JPanel buttonPanel = new JPanel();
        addButton(buttonPanel, "Start", event -> addBall());
        addButton(buttonPanel, "Clear", event -> clearBall());
        addButton(buttonPanel, "Close", event -> System.exit(0));
        add(buttonPanel, BorderLayout.SOUTH);
        pack();
        Thread paintTask = new Thread(() -> {
            for (;;) {
                ballComponent.paintComponent(ballComponent.getGraphics());
                try {
                    Thread.sleep(5L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        paintTask.start();
    }

    private void addButton(Container container, String title, ActionListener listener) {
        JButton button = new JButton(title);
        container.add(button);
        button.addActionListener(listener);
    }

    private void addBall() {
        Ball ball = new Ball();
        ballComponent.add(ball);
        Thread thread = new Thread(() -> {
            for (int i = 1; i <= STEPS; ++i) {
                ball.move(ballComponent.getBounds());
                try {
                    Thread.sleep(DELAY);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    private void clearBall() {
        ballComponent.clear();
        ballComponent.paintComponent(ballComponent.getGraphics());
    }
}
